<?php

namespace App\Http\Controllers\Admin;

use App\Models\ReadingTaskAppointUser;
use App\Models\ReadingTaskDatabase;
use App\Models\ReadingTaskExecute;
use Exception;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

/**
 * 阅读任务管理
 */
class ReadingTaskController extends CommonController
{
    protected $model;
    protected $validate;

    public function __construct()
    {
        parent::__construct();

        $this->model = new \App\Models\ReadingTask();
        $this->validate = new  \App\Validate\ReadingTaskValidate();
    }

    /**
     * 列表
     * @param page int 页码
     * @param limit int 分页大小
     * @param is_play string 是否发布   1 已发布  2 未发布
     * @param keywords string 搜索关键词
     * @param start_time datetime 任务开始时间    数据格式  年月日
     * @param end_time datetime 任务结束时间
     * @param create_start_time datetime 任务创建开始时间   数据格式 年月日时分秒
     * @param create_end_time datetime 任务创建结束时间
     */
    public function lists()
    {
        $page = $this->request->page ? intval($this->request->page) : 1;
        $limit = $this->request->limit ? intval($this->request->limit) : 10;
        $keywords = $this->request->keywords;
        $start_time = $this->request->start_time;
        $end_time = $this->request->end_time;
        $create_start_time = $this->request->create_start_time;
        $create_end_time = $this->request->create_end_time;
        $is_play = $this->request->is_play;

        $res = $this->model->lists(null, $keywords, null, $is_play, $start_time, $end_time, $create_start_time, $create_end_time, $limit);

        if ($res['total'] == 0 || !$res['data']) {
            return $this->returnApi(203, "暂无数据");
        }

        $readingTaskDatabaseModel = new ReadingTaskDatabase();
        foreach ($res['data'] as $key => $val) {
            $res['data'][$key]['intro'] = str_replace('&nbsp;', '', strip_tags($val['intro']));
            $res['data'][$key]['status'] = $this->model->getReadingTaskStatus($val);
            $dabatase_list = $readingTaskDatabaseModel->getReadingTaskDatabaseList($val['id']);
            $res['data'][$key]['number'] = count($dabatase_list);

            $res['data'][$key][$this->list_index_key] = $this->addSerialNumberOne($key, $page, $limit);
        }
        $res = $this->disPageData($res);
        return $this->returnApi(200, "查询成功", true, $res);
    }

    /**
     * 详情
     * @param id int 任务id
     */
    public function detail()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('detail')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $res = $this->model->detail($this->request->id);

        if (!$res) {
            return $this->returnApi(201, "参数传递错误");
        }
        if ($res['is_appoint'] == 1) {
            //获取指定用户信息
            $readingTaskAppointUserModel = new ReadingTaskAppointUser();
            $appoint_user_info = $readingTaskAppointUserModel->getAppointUserInfo($res->id, null, 999);
            $res->appoint_user_info = $appoint_user_info['data'];
        } else {
            $res->appoint_user_info = [];
        }

        //获取指定的数据库任务
        $readingTaskDatabaseModel = new ReadingTaskDatabase();
        $res->database_info = $readingTaskDatabaseModel->getReadingTaskDatabaseList($res->id);

        return $this->returnApi(200, "查询成功", true, $res->toArray());
    }

    /** 
     * 新增   
     * @param title string 任务名称    
     * @param img string 任务封面       
     * @param start_time int 开始时间
     * @param end_time string  结束时间
     * @param is_appoint 是否指定用户上传  1 指定  2 不指定（都可以上传）
     * @param appoint_user_id 指定用户id 多个 逗号拼接
     * @param is_reader int 报名是否需要绑定读者证   1.是   2.否(默认）
     * @param intro int 简介
     * @param database_id int 数据库id 多个逗号拼接
     * @param is_play 是否发布 1.发布 2.未发布    默认1
     */
    public function add()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('add')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $is_exists = $this->model->nameIsExists($this->request->title, 'title');
        if ($is_exists) {
            return $this->returnApi(202, "该直播名称已存在");
        }

        // 启动事务
        DB::beginTransaction();
        try {
            $data = [
                'title' => $this->request->title,
                'img' => $this->request->img,
                'start_time' => $this->request->start_time,
                'end_time' => $this->request->end_time,
                'is_appoint' => $this->request->is_appoint,
                'is_reader' => $this->request->is_reader,
                'intro' => $this->request->intro,
                'is_play' => $this->request->is_play,
            ];
            $this->model->add($data);
            //处理指定用户上传
            if ($this->request->is_appoint == 1) {
                if ($this->request->appoint_user_id) {
                    $readingTaskAppointUserModel = new ReadingTaskAppointUser();
                    $readingTaskAppointUserModel->interTableChange('task_id', $this->model->id, 'user_id', $this->request->appoint_user_id, 'add');
                }
            }
            //添加任务数据库数据
            if ($this->request->database_id) {
                $readingTaskDatabaseModel = new ReadingTaskDatabase();
                $readingTaskDatabaseModel->interTableChange('task_id', $this->model->id, 'database_id', $this->request->database_id, 'add');
            }
            // 提交事务
            DB::commit();
            return $this->returnApi(200, "新增成功", true);
        } catch (\Exception $e) {
            // 回滚事务
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }



    /** 
     * 修改
     * @param id string 任务id 
     * @param title string 任务名称    
     * @param img string 任务封面       
     * @param start_time int 开始时间
     * @param end_time string  结束时间
     * @param is_appoint 是否指定用户上传  1 指定  2 不指定（都可以上传）
     * @param appoint_user_id 指定用户id 多个 逗号拼接
     * @param is_reader int 报名是否需要绑定读者证   1.是   2.否(默认）
     * @param intro int 简介
     * @param database_id int 数据库id 多个逗号拼接 
     * @param is_play 是否发布 1.发布 2.未发布    默认1
     */
    public function change()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('change')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $id = $this->request->id;
        $res = $this->model->where('id', $id)->where('is_del', 1)->first();
        if (!$res) {
            return $this->returnApi(201, "参数传递错误");
        }

        if ($res->is_play == 1) {
            return $this->returnApi(201, "请先撤销，在进行修改！");
        }

        $is_exists = $this->model->nameIsExists($this->request->title, 'title', $this->request->id);
        if ($is_exists) {
            return $this->returnApi(202, "该阅读任务名称已存在");
        }
        $old_img = $res->img;


        //已有用户报名，不允许修改
        if ($res->is_reader !=  $this->request->is_reader) {
            //判断是否有人报名
            $readingTaskExecuteModel = new ReadingTaskExecute();
            $reading_status = $readingTaskExecuteModel->userIsExecute($id);
            if ($reading_status) {
                return $this->returnApi(201, "已有用户阅读，不能修改是否需要绑定读者证参数");
            }
        }
        // 启动事务
        DB::beginTransaction();
        try {
            $data = [
                'id' => $this->request->id,
                'title' => $this->request->title,
                'img' => $this->request->img,
                'start_time' => $this->request->start_time,
                'end_time' => $this->request->end_time,
                'is_appoint' => $this->request->is_appoint,
                'is_reader' => $this->request->is_reader,
                'intro' => $this->request->intro,
                'is_play' => $this->request->is_play,
            ];
            $this->model->change($data);
            //处理指定用户上传
            $readingTaskAppointUserModel = new ReadingTaskAppointUser();
            if ($this->request->is_appoint == 1) {
                if ($this->request->appoint_user_id) {
                    $readingTaskAppointUserModel->interTableChange('task_id', $this->model->id, 'user_id', $this->request->appoint_user_id, 'change');
                }
            } else {
                //删除所有的指定用户
                $readingTaskAppointUserModel->where('task_id', $this->model->id)->delete();
            }
            //添加任务数据库数据
            if ($this->request->database_id) {
                $readingTaskDatabaseModel = new ReadingTaskDatabase();
                $readingTaskDatabaseModel->interTableChange('task_id', $this->model->id, 'database_id', $this->request->database_id, 'change');
            }

            //删除旧资源
            if ($old_img != $this->request->img) {
                $this->deleteFile($old_img);
            }

            // 提交事务
            DB::commit();
            return $this->returnApi(200, "修改成功", true);
        } catch (\Exception $e) {
            // 回滚事务
            DB::rollBack();
            return $this->returnApi(202, "修改失败" . $e->getMessage());
        }
    }

    /**
     * 删除
     * @param id int 任务id
     */
    public function del()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('del')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $res = $this->model->detail($this->request->id, null, null);

        if (empty($res)) {
            return $this->returnApi(201, "参数传递错误");
        }
        $readingTaskExecuteModel = new ReadingTaskExecute();
        $is_exists = $readingTaskExecuteModel->userIsExecute($this->request->id);
        if ($is_exists) {
            return $this->returnApi(202, "此任务已有用户参与，不允许删除");
        }

        $res = $this->model->del($this->request->id);

        if ($res === true) {
            return $this->returnApi(200, "删除成功", true);
        }
        return $this->returnApi(202, $res);
    }

    /**
     * 撤销 和发布
     * @param id int 任务id
     * @param is_play int 发布   1 发布  2 撤销
     */
    public function cancelAndRelease()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('cancel_and_release')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        DB::beginTransaction();
        try {
            list($code, $msg) = $this->model->resumeAndCancel($this->request->id, 'is_play', $this->request->is_play);

            $is_play = $this->request->is_play == 1 ? '发布' : '撤销';

            DB::commit();
            return $this->returnApi($code, $is_play . $msg, $code === 200 ? true : false);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }
}
